<?php
/**
 * --------------------------------------------------
 * Copyright © 2021 成都拉风网络 版权所有
 *
 * 功能描述：
 *
 * 创建标识：Created by ZhongYuChan On 2021/4/9 10:03
 *
 * 修改标识：
 * 修改描述：
 *---------------------------------------------------
 */

namespace App\Common;


use App\Exceptions\AppSocketExceptions;
use App\YourApp\Constant\Role;

class Request
{
    /**
     * 连接的token
     * @var string
     */
    protected $token;

    /**
     * 解析token的参数
     * @var array
     */
    protected $param;

    /**
     * 连接的用户ID
     * @var int
     */
    protected $roleId;

    /**
     * 连接的用户类型
     * @var int
     */
    protected $roleType;

    /**
     * 附加数据
     * @var array
     */
    protected $ext;

    /**
     * 创建请求对象
     * @param string $token
     * @return Request
     * @throws AppSocketExceptions
     */
    public static function create($token){
        $request = new self();
        $param = Mcrypt::decode($token);

        if(empty($param) || empty($param['role_id']) || empty($param['role_type'])){
            throw new AppSocketExceptions("错误的token");
        }
        $request->initRole($param['role_id'],$param['role_type']);
        $request->init($param['ext']);
        return $request;
    }

    /**
     * 初始化用户身份
     * @param $roleId
     * @param $roleType
     */
    public function initRole($roleId,$roleType){
        $this->roleId = $roleId;
        $this->roleType = $roleType;
    }

    /**
     * 初始化请求内容
     * @param $ext
     */
    public function init($ext){
        $this->ext = $ext;
    }

    /**
     * 获取身份ID
     * @return int
     */
    public function roleId(){
        return $this->roleId;
    }

    /**
     * 获取身份类型
     * @return int
     */
    public function roleType(){
        return $this->roleType;
    }

    /**
     * 获取用户的uid
     * @return string
     * @throws AppSocketExceptions
     */
    public function roleUid(){
        if(!empty(Role::ROLE_MAP[$this->roleType()])){
            return Role::ROLE_MAP[$this->roleType()].$this->roleId();
        }
        throw new AppSocketExceptions("未知的用户类型");
    }

    /**
     * 获取附加数据
     * @param string $key
     * @param string $val
     * @return mixed|string
     */
    public function getExt($key = '*',$val = ''){
        return !empty($this->ext[$key]) ? $this->ext[$key] : $val;
    }
}